<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-3-18
 * Time: 上午11:28
 * 用户设置
 */
namespace Factory\Controller;
use Mcit\Page;
class SetController extends BaseController {

    public function index(){
//        P($_SESSION);
        $user = M("fac")->where("fac_login_name='".$_SESSION['fac_login_name']."'")->find();
        $this->user = $user;
        if(IS_POST){
//            P($_FILES);die;
            /*$data['name']           = I("name");
            $data['ip_port']        = I("ip_port");
            $data['key']            = I("key");
            $data['fac_name']       = I("fac_name");*/
            $logodirs  = strsToArrays($user['logo']);
            $logodir   = APP_ROOT_PATH."./Public/".$logodirs[1]."/".$logodirs[2]."/".$logodirs[3]."/".$logodirs[4];
            $portraitsdirs = strsToArrays($user['portrait']);
            $portraitdir  = APP_ROOT_PATH."./Public/".$portraitsdirs[1]."/".$portraitsdirs[2]."/".$portraitsdirs[3]."/".$portraitsdirs[4];
            if($_FILES['logo']['name'] != ''){
                $config = array(
                    'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                    'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                    'autoSub'       =>  true, //自动子目录保存文件
                    'subName'       =>  array('date', 'Ymd'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                    'rootPath'      =>     './Public/', //保存根路径
                    'savePath'      =>  './data/upload/face/', //保存路径
                    'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
                );
                $upload = new \Think\Upload($config); // 实例化上传类
                $info = $upload->uploadOne($_FILES['logo']);
                if (!$info) { // 上传错误提示错误信息
                    //$this->error($upload->getError());
                } else { // 上传成功 获取上传文件信息
                    $logo     = $info[savepath].$info[savename];
                    if(file_exists(APP_ROOT_PATH."./Public/".$user['logo'])){
                        unlink(APP_ROOT_PATH."./Public/".$user['logo']);
                    }
                    rmdir($logodir);
                }
            }
            if($_FILES['portrait']['name'] != ''){
                $configs = array(
                    'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                    'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                    'autoSub'       =>  true, //自动子目录保存文件
                    'subName'       =>  array('date', 'YmdHis'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                    'rootPath'      =>     './Public/', //保存根路径
                    'savePath'      =>  './data/upload/face/', //保存路径
                    'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
                );
                $uploads = new \Think\Upload($configs); // 实例化上传类
                $infos = $uploads->uploadOne($_FILES['portrait']);
                if (!$infos) { // 上传错误提示错误信息
                    //$this->error($uploads->getError());
                } else { // 上传成功 获取上传文件信息
                    $portrait = $infos[savepath].$infos[savename];
                    if(file_exists(APP_ROOT_PATH."./Public/".$user['portrait'])){
                        unlink(APP_ROOT_PATH."./Public/".$user['portrait']);
                    }
                    rmdir($portraitdir);
                }
            }
            $data['address']        = I("address");
            $data['background']     = I("background");
            $data['color']          = I("color");
            $data['logo']           = $logo;
            $data['portrait']       = $portrait;
            $map['fac_login_name']  = session('fac_login_name');
            $result = M('fac')->where($map)->save($data);

            if($result){
                $return['state'] = 100;
                $return['msg']   = '修改成功';
                $return['url']   = U('Login/logout');
            }else{
                $return['state'] = 200;
                $return['msg']   = '修改失败';
            }
            echo json_encode($return);
            exit;
        }
        $this->display();
    }
    //修改密码
    public function changePwd(){
        $user = M("fac")->where("fac_login_name='".$_SESSION['fac_login_name']."'")->find();
        if(IS_POST){
            $old_password  = I('old_password');
            $password  = I('fac_password');
            $password1 = I('fac_password1');
            //fac_type 区分厂商与运营商  2--厂商  3--运营商
            if($user['fac_password'] != $old_password && $user['fac_type'] == 2 || $user['fac_password'] != sha1($old_password) && $user['fac_type'] == 3){
                $return['state'] = 200;
                $return['msg']   = '原密码错误';
                echo json_encode($return);
                exit;
            }

            if($password != $password1){
                $return['state'] = 200;
                $return['msg']   = '两次密码输入不一致';
                echo json_encode($return);
                exit;
            }

            if(strlen($password)<8){
                $return['state'] = 200;
                $return['msg']   = '密码安全度不够';
                echo json_encode($return);
                exit;
            }
            //fac_type 区分厂商与运营商  2--厂商  3--运营商
            if($user['fac_type'] == 2){
                $data['fac_password']  = $password;
            }elseif($user['fac_type'] == 3){
                $data['fac_password']  = sha1($password);
            }

            $map['fac_login_name'] = session('fac_login_name');
            $result = M('fac')->where($map)->save($data);

            if($result){
                $return['state'] = 100;
                $return['msg']   = '修改成功';
                session(null);
                $return['url']   = U('Login/logout');
            }else{
                $return['state'] = 200;
                $return['msg']   = '修改失败';
            }
            echo json_encode($return);
            exit;
        }
        $this->user = $user;
        $this->display();
    }

    //用户列表
    public function user(){
//        P($_SESSION);
        $sql = "select * from ev_fac where pid='".session('uid')."'";
        $count = count(M()->query($sql));
        $Page  = new Page($count);
        // 重搜一律回第一页
        if( $_GET['fsign'] == "abnormal" ){
            $_GET['fsign'] = "normal";
            $_GET['page']  = 1;
        }
        if($_GET['page'] == 0){
            $nowPage = isset($_GET['page']) ? $_GET['page'] : 0;
        }else{
            $nowPage = isset($_GET['page']) ? $_GET['page'] * 20 - 20 : 0;
        }
        $sql1 = "select * from ev_fac where pid='".session('uid')."' limit $nowPage,".$Page->listRows;
        $user = M()->query($sql1);
        foreach($user as $k=>$v){
            $company = M("yy_role")->where("id='".$v['role']."'")->find();
            $user[$k]['roleName'] = $company['name'];
        }
        $this->pageView = $Page->show();
        $this->user     = $user;
        $this->display();

    }

    //站点查询（分配站点用）
    public function site(){
        if(!empty($_GET['nid'])){

            //fac_type 区分厂商与运营商  2--厂商  3--运营商
            if(session('fac_type') == 2){
                $sql  = "select a.id,a.name,a.yy_user_id,a.location,b.fullname from ev_plant a left join ev_region b on b.code = SUBSTRING_INDEX(a.location,',',-1) where a.plant_type=".session("fac_login_name");
            }elseif(session('fac_type') == 3){
                $sql  = "select a.id,a.name,a.yy_user_id,a.location,b.fullname from ev_plant a left join ev_region b on b.code = SUBSTRING_INDEX(a.location,',',-1) where a.plant_attr=".session("fac_type");
            }

            $site = M()->query($sql);
            /*$site = M()->getLastSql();
            echo json_encode($site);
            exit;*/
            foreach($site as $k =>$v){
                $site[$k]['nid'] = I("nid");
                $site[$k]['pid'] = M('fac')->where("id='".I('nid')."'")->getField("pid");
            }
            echo json_encode($site);
        }
    }

    //确定分配
    public function confirm(){
        $data['yy_user_id'] = I("yy_user_id");
        $ids = strsToArray($_POST['ids']);
        $map['id'] = array("IN",$ids);
        $result = M("plant")->where($map)->save($data);
        if($result){
            $return['state'] = 100;
            $return['msg']   = '分配成功！';
        }else{
            $return['state'] = 200;
            $return['msg']   = '分配失败,请重试！';
        }
        echo json_encode($return);
        exit;
    }

    //取消分配
    public function cancel(){
        if(session('pid') == 0){
            $data['yy_user_id'] = session('uid');
        }else{
            $data['yy_user_id'] = session('pid');
        }
        $ids = strsToArray($_POST['ids']);
        $map['id'] = array("IN",$ids);
        $result = M("plant")->where($map)->save($data);
        if($result){
            $return['state'] = 100;
            $return['msg']   = '取消成功！';
        }else{
            $return['state'] = 200;
            $return['msg']   = '取消失败,请重试！';
        }
        echo json_encode($return);
        exit;
    }

    //添加账号
    public function addUser(){
        if(IS_POST){
            $account = I('account');
            if(is_numeric($account)){
                $return['state'] = 200;
                $return['msg']   = "账号不能全是数字";
                echo json_encode($return);
                exit;
            }

            $map['fac_login_name'] = $account;

            if(M('fac')->where($map)->find()){
                $return['state'] = 200;
                $return['msg']   = "该账号已经使用";
                echo json_encode($return);
                exit;
            }

            $sqlData['role']           = I('role');
            $sqlData['pid']            = session('uid');
            $sqlData['fac_login_name'] = I('account');
            if(session('fac_type') == 2){
                $sqlData['fac_password']   = I('password');
                $sqlData['type']           = 2;
            }elseif(session('fac_type') == 3){
                $sqlData['fac_password']   = sha1(I('password'));
                $sqlData['type']           = 3;
            }
            $sqlData['fac_name']       = I('fac_name');
            $sqlData['address']        = I('address');
//            P($sqlData);die;
            $result = M('fac')->where($map)->add($sqlData);
            if($result){
                $return['state'] = 100;
                $return['msg']   = "添加成功";
                $return['url']   = U("Set/user",array('newid'=>$result));
            }else{
                $return['state'] = 200;
                $return['msg']   = "添加失败";
            }
            echo json_encode($return);
            exit;
        }else{
            //P($_SESSION);
            $map['state']   = 1;
            $map['id']      = array("neq",666);//系统管理员
            //fac_type 区分厂商与运营商  2--厂商  3--运营商
            if(session('fac_type') == 2){
                $map['type']   = 2;
            }elseif(session('fac_type') == 3){
                $map['type']   = 3;
            }
            $roleInfo       = M('yy_role')->where($map)->select();
            $this->roleInfo = $roleInfo;
            $this->display();
        }
    }
    //账号修改
    public function editUser(){
        if(IS_POST){
            $result = M('fac')->where("id='".I('uid')."'")->setField(array('role'=>I('role'),'fac_name'=>I('name'),'address'=>I('address')));
            if($result){
                $return['state'] = 100;
                $return['msg']   = M()->getLastSql();
                $return['url']   = U("Set/user",array('newid'=>$result));
            }else{
                $return['state'] = 200;
                $return['msg']   = "修改失败";
            }
            echo json_encode($return);
            exit;
        }else{
            $id = url_base64_decode(I('id'));
            $mapx['id'] = $id;
            $user = M('fac')->where($mapx)->find();
            $this->user = $user;

            $maprole['id']    = array("neq",666);
            $maprole['state'] = 1;
            //fac_type 区分厂商与运营商  2--厂商  3--运营商
            if(session('fac_type') == 2){
                $maprole['type']   = 2;
            }elseif(session('fac_type') == 3){
                $maprole['type']   = 3;
            }
            $roleInfo = M('yy_role')->where($maprole)->select();
            $this->roleInfo = $roleInfo;
            $this->display();
        }
    }

    //密码设置
    public function editFacPwd(){
        if(IS_POST){
            $map['id'] = I("id");
            $map['fac_login_name']  = I("fac_login_name");//账号
            $pwd1  = I("pwd1");//新密码
            $pwd2  = I("pwd2");//重复密码
            if($pwd1 == $pwd2){
                if(M('fac')->where("id='".$map['id']."' and fac_password='".$pwd2."' and fac_type=2")->find() || M('fac')->where("id='".$map['id']."' and fac_password='".sha1($pwd2)."' and fac_type=3")->find()){
                    $return['state'] = 100;
                    $return['msg']   = "保存成功！";
                    $return['url']   = U('Set/index');
                    echo json_encode($return);
                    exit;
                }else{
                    //fac_type 区分厂商与运营商  2--厂商  3--运营商
                    if(session('fac_type') == 2){
                        $data['fac_password'] = $pwd2;
                    }elseif(session('fac_type') == 3){
                        $data['fac_password'] = sha1($pwd2);
                    }

                    $result = M('fac')->where($map)->save($data);
                    if($result){
                        $return['state'] = 100;
                        $return['msg']   = '修改成功！';
                        $return['url']   = U('Set/index');
                    }else{
                        $return['state'] = 200;
                        $return['msg']   = '修改失败';
                    }
                }
            }else{
                $return['state'] = 200;
                $return['msg']   = '两次密码输入不一致，请重新输入！';
            }
            echo json_encode($return);
            exit;
        }
    }

    //删除用户
    public function delUser(){
        $map['id'] = I('id');
        if(session('pid') == 0){
            $yyid = session('uid');
        }else{
            $yyid = session('pid');
        }
        M("plant")->where("yy_user_id='".$map['id']."'")->save(array('yy_user_id'=>$yyid));
        $result = M('fac')->where($map)->delete();
        if($result){
            $return['state'] = 100;
            $return['msg']   = "删除账号成功";
        }else{
            $return['state'] = 200;
            $return['msg']   = "删除失败";
        }
        echo json_encode($return);
        exit;
    }

}